# -*- coding: utf-8 -*-
import time
'''
自选股服务设计
'''
_mongo = None

 
def user_portfolio(uid,page=0,count=10):
    '''分页方式读取用户的自选股 '''
    portfolio = []
    cursor = _mongo.portfolio.find({'uid':uid}).skip(page*count).limit(count)
    for s in cursor: portfolio.append(s)
    return portfolio

def add_stock(uid,code,name,tags=None):
    '''增加自选股'''
    item = {
        'uid': uid,
        'code': code,
        'name': name,
        'time': time.time()
    }
    if tags is not None and type(tags)==list:
        item['tags'] = tags
    if _mongo.portfolio.find_one({'uid':uid,'code':code},{'_id':1}) is None:
        _mongo.portfolio.save(item)
        return True
    else:
        return False
    

def del_stock(uid,code):
    '''删除自选股'''
    _mongo.portfolio.remove({'uid':uid,'code':code})
    
               
def add_tag(uid,code,tags):
    '''对自选股加标签--分组''' 
    if type(tags)==list:
        _mongo.portfolio.update({'uid':uid,'code':code},{'$addToSet':{'tags':{'$each':tags}} })
    else:
        _mongo.portfolio.update({'uid':uid,'code':code},{'$addToSet':{'tags':tags} })
  
    
def del_tag(uid,code,tags):  
    '''删除自选股标签--取消分组'''  
    if type(tags)==list:
        _mongo.portfolio.update({'uid':uid,'code':code},{'$pullAll':{'tags':tags} })
    else:
        _mongo.portfolio.update({'uid':uid,'code':code},{'$pull':{'tags':tags} })
    
   
if __name__=='__main__': 
    from pymongo import Connection  
    conn = Connection()
    _mongo = conn['promise']
    add_tag('hong', '600256', 'tag2')
    #del_stock('hong', '600256')
    #res = add_stock('hong', '600257', u'广汇股份2') 
    for s in user_portfolio('hong'): print s
